package com.clusterswisdom.horn.api.tmall.action.item;

import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.AbstractTmallAction;
import com.taobao.api.domain.Item;
import com.taobao.api.response.ItemUpdateResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
/**
 * 将商家上架商品库存全部修改为99
 * @author Jin_tian
 *
 */
public class SetItemsNumOfOnsaleAction extends AbstractTmallAction implements HornAction{
	@Override
	public HornResponse execute(ApiConfig config, JSONObject param)
		throws Exception {
		List<Item> items=getListOfItem(param);
		if(setNumOfItems(items)){
			return new HornResponse(true, "成功");
			
		}else{
			return new HornResponse(false, "失败");
			
		}
	}
	
	/**
	 * @param  无
	 * @return 商家出售中宝贝列表
	 * @throws Exception 
	 */
	public List<Item> getListOfItem(JSONObject param) throws Exception{
		int pageNo = 1;
		long totalNum = -1;
		
		List<Item> items = new LinkedList<Item>();
		do {
			param.put("page_no", pageNo++);
			ItemsOnsaleGetResponse response = (ItemsOnsaleGetResponse)TmallInstance.getInstance().executeRequest(param, "item", "itemsOnsaleGet");
			
			if (totalNum == -1) {
				totalNum = response.getTotalResults();
			}
		
			if(response.getItems() != null){
				items.addAll(response.getItems());
			}
			
		} while (items.size() < totalNum);
		
		return items;
	}
	
	/**
	 * @param 宝贝列表（商品的id不能为空）
	 * @return 全部设置是否成功
	 * @throws Exception 
	 */
	public boolean setNumOfItems(List<Item> items) {
		boolean hasError = false;
		JSONObject param=new JSONObject();
		
		for(Item item:items){
			param.put("num_iid", item.getNumIid());
			param.put("num","99");
			ItemUpdateResponse response = null;
			try {
				response = (ItemUpdateResponse)TmallInstance.getInstance().executeRequest(param, "item", "itemUpdate");
			} catch (Exception e) {
				e.printStackTrace();
			}
			hasError = !response.isSuccess();
		}
		
		return !hasError;
	}
}
